import { useDebounce } from '@shared/lib/hooks/debounceSearch'
import { IconFont } from '@shared/ui/IconFont'
import { useEffect, useState } from 'react'
import styles from './Search.module.scss'

interface ISearchProps {
  delay: number
  onChange?: (value: string) => void
  placeholder?: string
}

export const Search = ({ delay, onChange, placeholder }: ISearchProps) => {
  const [value, setValue] = useState('')

  const debounced = useDebounce(value, delay)

  useEffect(() => {
    onChange?.(debounced)
  }, [debounced])

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target
    setValue(value)
  }

  const cleanValue = () => {
    onChange?.('')
    setValue('')
  }

  return (
    <div className={styles['tasks-search']}>
      <input
        className={styles.input}
        onInput={handleChange}
        placeholder={placeholder}
        type='text'
        value={value}
      />
      {value ? (
        <div className={styles['clean-icon']} onClick={cleanValue}>
          <IconFont className={styles.icon} color='default' iconName='icon-close' />
        </div>
      ) : (
        <div>
          <IconFont className={styles.icon} color='default' iconName='icon-search' />
        </div>
      )}
    </div>
  )
}

export default Search
